const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 确保上传目录存在
const ensureDir = (dir) => {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
};

// 根据文件类型返回存储路径
const getUploadPath = (fileType) => {
  const baseDir = path.join(__dirname, '../uploads');
  switch(fileType) {
    case 'image':
      return path.join(baseDir, 'images');
    case 'video':
      return path.join(baseDir, 'videos');
    case 'document':
      return path.join(baseDir, 'documents');
    default:
      return path.join(baseDir, 'others');
  }
};

// 配置存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const fileType = file.mimetype.split('/')[0];
    const uploadPath = getUploadPath(fileType === 'image' ? 'image' :
      fileType === 'video' ? 'video' : 'document');
    ensureDir(uploadPath);
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, file.fieldname + '-' + uniqueSuffix + ext);
  }
});

// 文件过滤
const fileFilter = (req, file, cb) => {
  const fileTypes = /jpeg|jpg|png|gif|mp4|mov|avi|pdf|docx|txt/;
  const extname = fileTypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = fileTypes.test(file.mimetype);

  if (extname && mimetype) {
    return cb(null, true);
  } else {
    cb(new Error('Error: Unsupported file type'));
  }
};

module.exports = multer({
  storage,
  fileFilter,
  limits: {
    fileSize: 50 * 1024 * 1024 // 50MB
  }
});